using CustomerManagementSystem.Domain.Repositories;
using CustomerManagementSystem.Infrastructure.Data;
using Microsoft.EntityFrameworkCore;

namespace CustomerManagementSystem.Infrastructure.Repository;
public class EfRepository<T> : IRepository<T> where T : class
{
    private readonly CustomerDbContext _dbContext;
    private readonly DbSet<T> _dbSet;
    public EfRepository(CustomerDbContext dbContext)
    {
        _dbContext = dbContext;
        _dbSet = _dbContext.Set<T>();
    }
    public async Task<T> CreateAsync(T entity)
    {
        await _dbSet.AddAsync(entity);
        await _dbContext.SaveChangesAsync();
        return entity;
    }

    public async Task DeleteAsync(T entity)
    {
        _dbSet.Remove(entity);
        await _dbContext.SaveChangesAsync();
    }

    public async Task<IEnumerable<T>> GetAllAsync()
    {
        return await _dbSet.ToListAsync();
    }

    public async Task<T?> GetByIdAsync(Guid id)
    {
        return await _dbSet.FindAsync(id);
    }

    public async Task UpdateAsync(T entity)
    {
        _dbContext.Entry(entity).State = EntityState.Modified;
        await _dbContext.SaveChangesAsync();
    }
}